package com.hjtech.baselib.retroft

import android.util.Log
import com.google.gson.GsonBuilder
import com.zhong.kotlin.api.Constant
import com.zhong.kotlin.api.RequestImpl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/*
 * 项目名:    Pigeon
 * 包名       cn.hjtech.directory.common
 * 文件名:    BaseApi
 * 创建者:    ZJB
 * 创建时间:  2017/5/3 on 14:08
 * 描述:     TODO
 */
object BaseApi {

    fun getInstance(): RequestImpl {
        return init(Constant.BASE_URL).create(RequestImpl::class.java)
    }

    /**
     * 自定义OkHttpClient拦截请求参数并加上 加密参数
     */
    private val okHttpClient: OkHttpClient
        get() {
            val builder = OkHttpClient.Builder()
            val level = HttpLoggingInterceptor.Level.HEADERS
            val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.d("ApiUrl", "--->" + message) })
            loggingInterceptor.level = level//日志显示级别
            builder.addInterceptor(loggingInterceptor) //新建log拦截器
            builder.connectTimeout(15, TimeUnit.SECONDS)//设置超时
            builder.readTimeout(15, TimeUnit.SECONDS)
            builder.writeTimeout(15, TimeUnit.SECONDS)
            builder.retryOnConnectionFailure(true)//错误重连
            return builder.build()
        }

    fun init(baseUrl: String): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder()
                        .setLenient()
                        .create()
                ))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .build()

    }
}
